package com.jushu.storbox.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.RoundingMode;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.TrafficStats;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build.VERSION;
import android.os.Environment;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.jushu.storbox.LoginActivity;
import com.jushu.storbox.R;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.manager.ActivityTaskManager;
import com.jushu.storbox.service.UserControl;
import com.huawei.sharedrive.sdk.android.exception.ClientException;

/**
 * Public tools class
 * 
 */
public class PublicTools {
	/**
	 * date convert to string
	 * 
	 * @param date
	 * @return
	 */
	public static String dataToString(Date date) {
		String nowTime = null;
		if (null != date) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			nowTime = sdf.format(date);
		}
		return nowTime;
	}

	/***
	 * @param DBTime
	 * @return
	 */
	public static String getFormatData(Context context, long DBTime) {

		Date DBDate = new Date(DBTime);
		long currentTime = System.currentTimeMillis();
		Date date = new Date(currentTime);
		String pattern = "yyyy-MM-dd a hh:mm";
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		String stringTime = format.format(date);
		String dbTime = format.format(DBDate);

		String[] DB = dbTime.split(" ");
		String[] CT = stringTime.split(" ");

		String[] DBS = DB[0].split("-");
		String[] CTS = CT[0].split("-");

		if (DBS[0].equals(CTS[0])) {
			if (DBS[1].equals(CTS[1])) {
				if (DBS[2].equals(CTS[2])) {
					return (context.getString(R.string.publictools_formatdata_recently_upgrade) + DB[1] + DB[2]);
				} else {
					int da = Integer.parseInt(CTS[2]) - Integer.parseInt(DBS[2]);
					if (da == 1) {
						String out = context.getString(R.string.publictools_formatdata_yestoday);
						return (context.getString(R.string.publictools_formatdata_recently_upgrade) + out);
					} else {
						String out = da + context.getString(R.string.publictools_formatdata_days_ago);
						return (context.getString(R.string.publictools_formatdata_recently_upgrade) + out);
					}
				}
			} else {
				int mon = Integer.parseInt(CTS[1]) - Integer.parseInt(DBS[1]);
				if (mon == 1) {
					String out = context.getString(R.string.publictools_formatdata_last_month);
					return (context.getString(R.string.publictools_formatdata_recently_upgrade) + out);
				} else {
					String out = mon + context.getString(R.string.publictools_formatdata_months_ago);
					return (context.getString(R.string.publictools_formatdata_recently_upgrade) + out);
				}
			}
		} else {
			return (context.getString(R.string.publictools_formatdata_recently_upgrade) + "long long ago");
		}

	}

	/**
	 * long convert to string
	 * 
	 * @param date
	 * @return
	 */
	@SuppressLint("SimpleDateFormat")
	public static String longToString(long longData) {
		String stringDate = "";
		try {
			SimpleDateFormat simpleData = new SimpleDateFormat("yyyy/MM/dd HH:mm");
			if (0l != longData) {
				Date date = new Date(longData);
				stringDate = simpleData.format(date);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return stringDate;
	}

	/**
	 * long convert to string
	 * 
	 * @param date
	 * @return
	 */
	public static String longToStringSimple(long longData) {
		SimpleDateFormat simpleData = new SimpleDateFormat("MM/dd hh:mm");
		Date date = new Date(longData);
		String stringDate = simpleData.format(date);
		return stringDate;
	}

	public static void createLocalFolad() {

		File downloadPath = new File(ClientConfig.FILEDOWNLOADPATH);
		if (!downloadPath.exists()) {
			downloadPath.mkdirs();
		}
		File logPath = new File(ClientConfig.FILELOGPATH);
		if (!logPath.exists()) {
			logPath.mkdirs();
		}

	}

	/**
	 * open file
	 * 
	 * @param context
	 * @param file
	 */
	public static void openFile(Context context, String file) {
		try {
			File downloadPath = new File(file);
			Intent intent = new Intent();
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setAction(Intent.ACTION_VIEW);
			String type = getMIMEType(downloadPath);
			intent.setDataAndType(/* uri */Uri.fromFile(downloadPath), type);
			context.startActivity(intent);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	/**
	 * Get file mime type
	 * 
	 * @param path
	 * @return
	 */
	public static String getMIMEType(File file) {

		String type = "*/*";
		String fName = file.getName();
		int dotIndex = fName.lastIndexOf(".");
		if (dotIndex < 0) {
			return type;
		}
		String end = fName.substring(dotIndex, fName.length()).toLowerCase();
		if (end == "")
			return type;
		for (int i = 0; i < MIME_MapTable.length; i++) {
			if (end.equals(MIME_MapTable[i][0]))
				type = MIME_MapTable[i][1];
		}
		return type;
	}

	/** MIME MapTable */
	public static final String[][] MIME_MapTable = { { ".3gp", "video/3gpp" }, { ".apk", "application/vnd.android.package-archive" },
			{ ".asf", "video/x-ms-asf" }, { ".avi", "video/x-msvideo" }, { ".bin", "application/octet-stream" }, { ".bmp", "image/bmp" },
			{ ".c", "text/plain" }, { ".class", "application/octet-stream" }, { ".conf", "text/plain" }, { ".cpp", "text/plain" },
			{ ".doc", "application/msword" }, { ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" },
			{ ".xls", "application/vnd.ms-excel" }, { ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },
			{ ".exe", "application/octet-stream" }, { ".gif", "image/gif" }, { ".gtar", "application/x-gtar" }, { ".gz", "application/x-gzip" },
			{ ".h", "text/plain" }, { ".htm", "text/html" }, { ".html", "text/html" }, { ".jar", "application/java-archive" }, { ".java", "text/plain" },
			{ ".jpeg", "image/jpeg" }, { ".jpg", "image/jpeg" }, { ".js", "application/x-javascript" }, { ".log", "text/plain" },
			{ ".m3u", "audio/x-mpegurl" }, { ".m4a", "audio/mp4a-latm" }, { ".m4b", "audio/mp4a-latm" }, { ".m4p", "audio/mp4a-latm" },
			{ ".m4u", "video/vnd.mpegurl" }, { ".m4v", "video/x-m4v" }, { ".mov", "video/quicktime" }, { ".mp2", "audio/x-mpeg" }, { ".mp3", "audio/x-mpeg" },
			{ ".mp4", "video/mp4" }, { ".mpc", "application/vnd.mpohun.certificate" }, { ".mpe", "video/mpeg" }, { ".mpeg", "video/mpeg" },
			{ ".mpg", "video/mpeg" }, { ".mpg4", "video/mp4" }, { ".mpga", "audio/mpeg" }, { ".msg", "application/vnd.ms-outlook" }, { ".ogg", "audio/ogg" },
			{ ".pdf", "application/pdf" }, { ".png", "image/png" }, { ".pps", "application/vnd.ms-powerpoint" }, { ".ppt", "application/vnd.ms-powerpoint" },
			{ ".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" }, { ".prop", "text/plain" }, { ".rc", "text/plain" },
			{ ".rmvb", "audio/x-pn-realaudio" }, { ".rtf", "application/rtf" }, { ".sh", "text/plain" }, { ".tar", "application/x-tar" },
			{ ".tgz", "application/x-compressed" }, { ".txt", "text/plain" }, { ".wav", "audio/x-wav" }, { ".wma", "audio/x-ms-wma" },
			{ ".wmv", "audio/x-ms-wmv" }, { ".wps", "application/vnd.ms-works" }, { ".xml", "text/plain" }, { ".z", "application/x-compress" },
			{ ".zip", "application/x-zip-compressed" }, { "", "text/*" } };

	/**
	 * open File
	 * 
	 * @param filePath
	 *            String
	 * @return Intent
	 */
	public static Intent openFile(String filePath) {

		File file = new File(filePath);
		if (!file.exists())
			return null;
		String end = file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length()).toLowerCase();
		if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
			return getAudioFileIntent(filePath);
		} else if (end.equals("3gp") || end.equals("mp4")) {
			return getAudioFileIntent(filePath);
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg") || end.equals("bmp")) {
			return getImageFileIntent(filePath);
		} else if (end.equals("apk")) {
			return getApkFileIntent(filePath);
		} else if (end.equals("ppt")) {
			return getPptFileIntent(filePath);
		} else if (end.equals("xls")) {
			return getExcelFileIntent(filePath);
		} else if (end.equals("doc")) {
			return getWordFileIntent(filePath);
		} else if (end.equals("pdf")) {
			return getPdfFileIntent(filePath);
		} else if (end.equals("chm")) {
			return getChmFileIntent(filePath);
		} else if (end.equals("txt")) {
			return getTextFileIntent(filePath, false);
		} else {
			return getAllIntent(filePath);
		}
	}

	/**
	 * @param param
	 *            String
	 * @return Intent
	 */
	public static Intent getAllIntent(String param) {

		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "*/*");
		return intent;
	}

	/**
	 * 
	 * @param param
	 *            String
	 * @return Intent
	 */
	public static Intent getApkFileIntent(String param) {

		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		return intent;
	}

	/**
	 * @param param
	 *            String
	 * @return Intent
	 */
	public static Intent getVideoFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("oneshot", 0);
		intent.putExtra("configchange", 0);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "video/*");
		return intent;
	}

	/**
	 * @param param
	 *            String
	 * @return Intent
	 */
	public static Intent getAudioFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("oneshot", 0);
		intent.putExtra("configchange", 0);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "audio/*");
		return intent;
	}

	/**
	 * @param param
	 *            String
	 * @return Intent
	 */
	public static Intent getHtmlFileIntent(String param) {

		Uri uri = Uri.parse(param).buildUpon().encodedAuthority("com.android.htmlfileprovider").scheme("content").encodedPath(param).build();
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.setDataAndType(uri, "text/html");
		return intent;
	}

	/**
	 * @param param
	 *            String
	 * @return Intent
	 */
	public static Intent getImageFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "image/*");
		return intent;
	}

	/**
	 * @param param
	 *            String
	 * @return Intent
	 */
	public static Intent getPptFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
		return intent;
	}

	/**
	 * @param param
	 *            String
	 * @return Intent
	 */
	public static Intent getExcelFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/vnd.ms-excel");
		return intent;
	}

	/**
	 * @param param
	 *            String
	 * @return Intent
	 */
	public static Intent getWordFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/msword");
		return intent;
	}

	/**
	 * @param param
	 *            String
	 * @return Intent
	 */
	public static Intent getChmFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/x-chm");
		return intent;
	}

	/**
	 * @param param
	 *            String
	 * @param paramBoolean
	 *            boolean
	 * @return Intent
	 */
	public static Intent getTextFileIntent(String param, boolean paramBoolean) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		if (paramBoolean) {
			Uri uri1 = Uri.parse(param);
			intent.setDataAndType(uri1, "text/plain");
		} else {
			Uri uri2 = Uri.fromFile(new File(param));
			intent.setDataAndType(uri2, "text/plain");
		}
		return intent;
	}

	/**
	 * @param param
	 *            String
	 * @return Intent
	 */
	public static Intent getPdfFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/pdf");
		return intent;
	}

	/**
	 * @param source
	 *            String
	 * @return String
	 */
	public static String changeBKM(String source) {
		DecimalFormat df = new DecimalFormat("#.##");
		df.setRoundingMode(RoundingMode.DOWN);
		if (null == source)
			return df.format(0) + "B";
		int length = source.length();
		if (length == 0) {
			return df.format(0) + "B";
		} else if (length < 4 && length > 0) {
			return df.format(Double.valueOf(source)) + "B";
		} else if (length >= 4 && length < 8) {
			if ((df.format(Double.parseDouble(source) / 1024)).replace(".", "/").split("/")[0].length() > 3) {
				return df.format(Double.parseDouble(source) / 1024 / 1024) + "MB";
			}
			return df.format(Double.parseDouble(source) / 1024) + "KB";
		} else {
			return df.format(Double.parseDouble(source) / 1024 / 1024) + "MB";
		}
	}

	public static long getCurrentTime() {
		long currentMills = System.currentTimeMillis();
		return currentMills;
	}

	public static Long timeStampToLong(Timestamp ts) {

		if (null != ts) {
			Date date = new Date();
			try {
				date = ts;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
			return date.getTime();
		}
		return null;
	}

	public static String getClientUserName(Context context) {
		String username = "";
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
//			username = settings.getString(ClientConfig.CURRENTUSERNAME, "");
			username = settings.getString(ClientConfig.USERNAME, "");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return username;
	}

	public static void setClientUserName(Context context, String userName) {
		//
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			Editor editor = settings.edit();
//			editor.putString(ClientConfig.CURRENTUSERNAME, checkUserNameFormat(userName));
			editor.putString(ClientConfig.USERNAME, userName);
			editor.commit();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public static void setClientUserPassFail(Context context, String password) {
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			Editor editor = settings.edit();
			String strContent = "";
			if (password.length() > 2) {
				strContent = AESEncryptorUtil.encryptAndBase64(AESEncryptorUtil.getSpesPwd(), password);
			} else {
				strContent = "";
			}
			editor.putString(ClientConfig.CURRENTPASSWORD, strContent);
			editor.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void setClientUserLoackPassFail(Context context, String password) {
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			Editor editor = settings.edit();
			String strContent = "";
			if (password.length() > 2) {
				strContent = AESEncryptorUtil.encryptAndBase64(AESEncryptorUtil.getSpesPwd(), password);
			} else {
				strContent = "";
			}
			editor.putString(ClientConfig.LOACKPASSWORE, strContent);
			editor.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getClientUserLoackPassFail(Context context) {
		String password = "";
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			String strContent = settings.getString(ClientConfig.LOACKPASSWORE, "");
			if (strContent.length() > 2) {
				password = AESEncryptorUtil.decryptAndBase64(AESEncryptorUtil.getSpesPwd(), strContent);
			}
		} catch (Exception e) {
			e.printStackTrace();
			password = "";
		}
		return password;
	}

	public static String checkUserNameFormat(String uName) {
		uName = uName.toLowerCase().trim();
		String userName = uName;
		try {
			if (uName.contains("\\")) {
				userName = uName.substring(uName.indexOf('\\') + 1, uName.length());
			} else if (uName.contains("/")) {
				userName = uName.substring(uName.indexOf('/') + 1, uName.length());
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return userName;
	}

	public static String getClientUserPassFail(Context context) {
		String password = "";
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			String strContent = settings.getString(ClientConfig.CURRENTPASSWORD, "");
			if (strContent.length() > 2) {
				password = AESEncryptorUtil.decryptAndBase64(AESEncryptorUtil.getSpesPwd(), strContent);
			}
		} catch (Exception e) {
			e.printStackTrace();
			password = "";
		}
		return password;
	}

	public static String getEncryptorPassword(Context context) {
		String password = "";
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			password = settings.getString(ClientConfig.CURRENTPASSWORD, "");
		} catch (Exception e) {
			e.printStackTrace();
			password = "";
		}
		return password;
	}

	public static String getLoginUserName(Context context) {
		String username = "";
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			username = settings.getString(ClientConfig.USERNAME, "");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return username;
	}

	public static void setLoginUserName(Context context, String userName) {
		//
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			Editor editor = settings.edit();
//			editor.putString(ClientConfig.USERNAME, checkUserNameFormat(userName));
			editor.putString(ClientConfig.USERNAME, userName);
			editor.commit();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public static void setLoginUserPassFail(Context context, String password) {
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			Editor editor = settings.edit();
			String strContent = "";
			if (password.length() > 2) {
				strContent = AESEncryptorUtil.encryptAndBase64(AESEncryptorUtil.getSpesPwd(), password);
			} else {
				strContent = "";
			}
			editor.putString(ClientConfig.LOGINPASSWORD, strContent);
			editor.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static String getEncryptorLoginPassFail(Context context) {
		String password = "";
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			password = settings.getString(ClientConfig.LOGINPASSWORD, "");
		} catch (Exception e) {
			e.printStackTrace();
			password = "";
		}
		return password;
	}
	
	public static String getLoginUserPassFail(Context context) {
		String password = "";
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			String strContent = settings.getString(ClientConfig.LOGINPASSWORD, "");
			if (strContent.length() > 2) {
				password = AESEncryptorUtil.decryptAndBase64(AESEncryptorUtil.getSpesPwd(), strContent);
			}
		} catch (Exception e) {
			e.printStackTrace();
			password = "";
		}
		return password;
	}
	
	public static boolean isLoginSuccess(Context context) {
		boolean loginStatus = false;
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			loginStatus = settings.getBoolean(ClientConfig.LOGIN_STATE, false);
		} catch (Exception e) {
			e.printStackTrace();
			loginStatus = false;
		}
		return loginStatus;
	}

	/**
	 * get cloud drive client version code
	 * 
	 * @return int version code
	 */
	public static int getVersionCode(Context context) {
		int versionCode = 0;
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			versionCode = info.versionCode;

		} catch (NameNotFoundException e) {
			e.printStackTrace();
			versionCode = 0;
		}
		return versionCode;
	}

	/**
	 * get cloud drive client version name
	 * 
	 * @return String version name
	 */
	public static String getVersionName(Context context) {
		String versionName = "1.0";
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			versionName = info.versionName;

		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionName;
	}

	public static String getDeviceIMEI(Context context) {
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
		Editor editor = settings.edit();
		String imei = settings.getString("DeviceIMEI", "");
		if (null == imei || "".equals(imei)) {
			imei = tm.getDeviceId();
			if (null != imei && !"".equals(imei)) {
				editor.putString("DeviceIMEI", imei);
				editor.commit();
			}
		}
		return imei;
	}

	public static String getDeviceSIMNum(Context context) {
		String sim = "unknow";
		try {
			TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
			sim = tm.getSimSerialNumber();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return sim;
	}

	public static String getDeviceIPAddress() {
		//
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) {

						return inetAddress.getHostAddress();
					}
				}
			}
		} catch (SocketException e) {

		}
		return null;
	}

	public static String getNetworkType(Context context) {
		WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		String wlanSSID = "";
		if (wifi != null) {
			WifiInfo info = wifi.getConnectionInfo();
			if (info != null) {
				wlanSSID = info.getSSID();
				if (null == wlanSSID || "".equals(wlanSSID)) {
					wlanSSID = "3G/2G";
				} else {
					wlanSSID = "WIFI";
				}
			} else {
				wlanSSID = "3G/2G";
			}
		}
		return wlanSSID;
	}

	public static String getFormatCurTime() {
		long receiveDate = System.currentTimeMillis();
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(receiveDate);
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String parseData = dateformat.format(calendar.getTime());
		return parseData;
	}

	public static String getOSVersion() {

		return android.os.Build.VERSION.RELEASE;
	}

	public static String getDeviceVersion() {

		return android.os.Build.DISPLAY;
	}

	public static boolean isAppExist(Context context, boolean flag, String pkg, int verCode) {
		int versionCode = 0;
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(pkg, 0);
			versionCode = info.versionCode;
			if (!flag) {
				return true;
			} else {
				return (verCode < versionCode || verCode == versionCode);
			}
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * @param context
	 * @return
	 */
	public static String getCloudDrivePkg(Context context) {
		String packageName = "com.jushu.storbox";
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			packageName = info.packageName;
		} catch (Exception e) {
			e.printStackTrace();
			packageName = "com.jushu.storbox";
		}
		return packageName;
	}

	/**
	 * @param context
	 * @return
	 */
	public static void clearRMSDocmentCache() {
		try {
			File rootFolder = new File(ClientConfig.FILEDATARMSPATH);
			rootFolder.delete();
			if (rootFolder.exists()) {
				File[] files = rootFolder.listFiles();
				for (File file : files) {
					file.delete();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param absPath
	 * @return
	 */
	public static boolean deleteFileCache(String absPath) {
		if (absPath == null)
			return false;
		File file = new File(absPath);
		if (file.exists()) {
			File[] files = file.listFiles();
			for (File f : files) {
				if (!deleteFileAll(f.getAbsolutePath()))
					return false;
			}
			return true;
		} else {
			return false;
		}

	}

	/**
	 * @param absPath
	 * @return
	 */
	public static boolean deleteFileAll(String absPath) {
		if (absPath == null) {
			return false;
		}
		File file = new File(absPath);
		if (!file.exists()) {
			return false;
		}
		if (file.isFile()) {
			return file.delete();
		} else if (file.isDirectory()) {
			File[] files = file.listFiles();
			if (files.length == 0)
				return file.delete();
			for (File f : files) {
				if (!deleteFileAll(f.getAbsolutePath()))
					return false;
			}
			return file.delete();
		}
		return false;
	}

	public static boolean isLocaleLanguageCN() {
		Locale l = Locale.getDefault();
		if ("zh".equals(l.getLanguage())) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * is img or not
	 * 
	 * @param types
	 * @param name
	 * @return boolean true: is img false:is not
	 */
	public static boolean isFileType(String name, String[] types) {
		boolean flag = false;
		if (name == null) {
			return flag;
		}
		for (String type : types) {
			if (name.toLowerCase().endsWith(type.toLowerCase())) {
				flag = true;
				break;
			}
		}
		return flag;
	}

	/**
	 * 
	 * */
	/**
	 * get cloudDrive rms in device
	 * 
	 * @return
	 */
	public static double getCloudDriveRMSDocmentSize() {
		final String cloudDrivePath = ClientConfig.FILEDATARMSPATH;
		return getFolderSize(cloudDrivePath);
	}

	/**
	 * get Folder Size in device
	 * 
	 * @param folderPath
	 *            String
	 * @return double
	 */
	private static double getFolderSize(String folderPath) {
		double size = 0;
		try {
			File f = new File(folderPath);
			if (f.exists()) {
				File flist[] = f.listFiles();
				if (null != flist) {
					for (int i = 0; i < flist.length; i++) {
						if (flist[i].isDirectory()) {
							size = size + getFolderSize(flist[i].getAbsolutePath());
						} else {
							size = size + flist[i].length();
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			size = 0;
		}
		return size;
	}

	/***
	 * 
	 * @param context
	 * @param des
	 */
	public static void setDes(Context context, String des) {
		@SuppressWarnings("static-access")
		SharedPreferences prefs = context.getSharedPreferences(ClientConfig.settings, context.MODE_APPEND);
		Editor editor = prefs.edit();
		editor.putString(ClientConfig.CLOUD_DES, des);
		editor.commit();
	}

	/***
	 * @param context
	 * @return
	 */
	public static String getDes(Context context) {
		@SuppressWarnings("static-access")
		SharedPreferences prefs = context.getSharedPreferences(ClientConfig.settings, context.MODE_APPEND);
		String res = prefs.getString(ClientConfig.CLOUD_DES, "DESC");
		return res;
	}

	/***
	 * @param context
	 * @param orderBy
	 */
	public static void setOrderBy(Context context, String orderBy) {
		@SuppressWarnings("static-access")
		SharedPreferences prefs = context.getSharedPreferences(ClientConfig.settings, context.MODE_APPEND);
		Editor editor = prefs.edit();
		editor.putString(ClientConfig.CLOUD_ORDERBY, orderBy);
		editor.commit();
	}

	/***
	 * @param context
	 * @return orderBy
	 */
	public static String getOrderBy(Context context) {
		@SuppressWarnings("static-access")
		SharedPreferences prefs = context.getSharedPreferences(ClientConfig.settings, context.MODE_APPEND);
		String res = prefs.getString(ClientConfig.CLOUD_ORDERBY, "modifiedAt");
		return res;
	}

	/***
	 * @return boolean true:root ; false not root
	 */
	public static boolean mdmRootCheck() {
		return false;
	}

	public static void clearData(final Context context) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				clearCloudDriveData(context);
			}
		}).start();
	}

	/**
	 * @param handler
	 */
	public static void clearCloudDriveData(Context context) {
		try {
			// deleteFileCache(DirectoryTools.getCurrentThumbnailPath(context));
			// deleteFileCache(DirectoryTools.getCurrentSharedThumbnailPath(context));
			deleteFileCache(DirectoryUtil.generateTempDir(context));
			deleteFileCache(DirectoryUtil.generateDownloadDir(context));
			deleteFileCache(DirectoryUtil.generateShareDir(context));
			deleteFileCache(ClientConfig.ONEBOX_TAKE_PHOHO_DIC);
			deleteFileCache(ClientConfig.FILEDATARMSPATH);
			// deleteFileCache(ClientConfig.BASEPATH);
			deleteFileCache("/data/data/" + context.getPackageName() + "/" + "tmpFile/");
			DAOFactory.instance(context).getFileDao().cleanCatch();// .deleteAll();
			DAOFactory.instance(context).getFolderDao().cleanCatch();// .deleteAll();
			DAOFactory.instance(context).getShareFileDao().cleanCatch();// .deleteAll();
			DAOFactory.instance(context).getShareFolderDao().cleanCatch();// .deleteAll();
			DAOFactory.instance(context).getShareINodeDao().cleanCatch();// .deleteAll();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	/***
	 * @param context
	 * @param downloadRemind
	 */
	public static void setDownloadRemind(Context context, boolean downloadRemind) {
		@SuppressWarnings("static-access")
		SharedPreferences prefs = context.getSharedPreferences(ClientConfig.settings, context.MODE_APPEND);
		Editor editor = prefs.edit();
		editor.putBoolean(ClientConfig.CLOUD_DOWNLOADREMIND, downloadRemind);
		editor.commit();
	}

	/***
	 * @param context
	 * @return boolean
	 */
	public static boolean getDownloadRemind(Context context) {
		@SuppressWarnings("static-access")
		SharedPreferences prefs = context.getSharedPreferences(ClientConfig.settings, context.MODE_APPEND);
		return prefs.getBoolean(ClientConfig.CLOUD_DOWNLOADREMIND, true);
	}

	/***
	 * @param context
	 */
	public static void setAlbumBackup(Context context, boolean albumBackup) {
		@SuppressWarnings("static-access")
		SharedPreferences prefs = context.getSharedPreferences(ClientConfig.settings, context.MODE_APPEND);
		Editor editor = prefs.edit();
		editor.putBoolean(ClientConfig.ALBUM_BACKUP, albumBackup);
		editor.commit();
	}

	/***
	 * @param context
	 * @return boolean
	 */
	public static boolean getAlbumBackup(Context context) {
		@SuppressWarnings("static-access")
		SharedPreferences prefs = context.getSharedPreferences(ClientConfig.settings, context.MODE_APPEND);
		return prefs.getBoolean(ClientConfig.ALBUM_BACKUP, false);
	}

	/***
	 * getFileSize
	 * 
	 * @param filePath
	 * @return boolean
	 */
	public static long getFileSize(String filePath) {
		// TODO Auto-generated method stub
		File file = new File(filePath);
		long size = 0;
		if (file.exists()) {
			FileInputStream fis = null;
			try {
				fis = new FileInputStream(file);
				size = fis.available();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					if (null != fis) {
						fis.close();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} else {

		}
		return size;
	}

	/***
	 * @param context
	 * @param packageName
	 * @return
	 */
	public static boolean serviceIsRunning(Context context, String serviceName) {
		ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager.getRunningServices(1000);
		for (int i = 0; i < runningService.size(); i++) {
			if (runningService.get(i).service.getClassName().toString().equals(serviceName)) {
				return true;
			}
		}
		return false;
	}

	public static void setExpiredAt(Context context, long lifeTime) {

		try {
			long expiredAt = System.currentTimeMillis() + (lifeTime * Constant.SECOND);
			Date date = new Date(expiredAt);
			SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			LogUtil.d("PublicTools", "token timeout is:" + dateformat.format(date));
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			Editor editor = settings.edit();
			editor.putLong(ClientConfig.EXPIREDAT, expiredAt);
			editor.commit();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public static long getExpiredAt(Context context) {
		long expiredAt = 0l;
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			expiredAt = settings.getLong(ClientConfig.EXPIREDAT, 0l);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return expiredAt;
	}

	public static void setRefreshToken(Context context, String refreshToken) {
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			Editor editor = settings.edit();
			editor.putString(ClientConfig.REFRESHTOKEN, refreshToken);
			editor.commit();

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public static String getRefreshToken(Context context) {
		String refreshToken = "";
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			refreshToken = settings.getString(ClientConfig.REFRESHTOKEN, "");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return refreshToken;
	}

	public static void setAuthorization(Context context, String authorization) {
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			Editor editor = settings.edit();
			editor.putString(ClientConfig.AUTHORIZATION, authorization);
			editor.commit();

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public static String getAuthorization(Context context) {
		String authorization = "";
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			authorization = settings.getString(ClientConfig.AUTHORIZATION, "");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return authorization;
	}

	public static void setOwnerId(Context context, String ownerId) {
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			Editor editor = settings.edit();
			editor.putString(ClientConfig.OWNERID, ownerId);
			editor.commit();

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public static String getOwnerId(Context context) {
		String ownerId = null;
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			ownerId = settings.getString(ClientConfig.OWNERID, "");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ownerId;
	}

	public static void setServerAddress(Context context, String serverAddress) {
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			settings.edit().putString(ClientConfig.SERVER_ADDRESS, serverAddress).commit();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getServerAddress(Context context) {
		String serverAddress = "";
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			serverAddress = settings.getString(ClientConfig.SERVER_ADDRESS, "");
			serverAddress = getCorrectUrl(serverAddress);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return serverAddress;
	}

	public static void setCleanTempTime(Context context, long cleanTempTime) {
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			Editor editor = settings.edit();
			editor.putLong(ClientConfig.CLEANTEMPTIME, cleanTempTime);
			editor.commit();

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public static long getCleanTempTime(Context context) {
		long cleanTempTime = 0l;
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			cleanTempTime = settings.getLong(ClientConfig.CLEANTEMPTIME, 0l);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cleanTempTime;
	}

	/*
	 * @return void
	 */
	public static void installApk(Context context, String pathName) {
		try {
			if (new File(pathName).exists()) {
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.fromFile(new File(pathName)), "application/vnd.android.package-archive");
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);
			} else {
				Toast.makeText(context, context.getString(R.string.install_newversion_fail), Toast.LENGTH_LONG).show();
			}
		} catch (Exception e) {
			LogUtil.e("installApk fail " + e.getMessage());
		}
	}

	/*
	 * @parm context
	 * 
	 * @return void
	 */
	public static void finishActivity(Context context) {
		try {
			if (null != context) {
				Activity activity = (Activity) context;
				activity.finish();
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public static void setScrollViewHeight(Context context, int height) {
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			Editor editor = settings.edit();
			editor.putInt(ClientConfig.SCROLLVIEWHEIGHT, height);
			editor.commit();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public static int getScrollViewHeight(Context context) {
		int height = 0;
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			height = settings.getInt(ClientConfig.SCROLLVIEWHEIGHT, 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return height;
	}

	public static void setItemHeight(Context context, int height) {
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			Editor editor = settings.edit();
			editor.putInt(ClientConfig.ITEMVIEW, height);
			editor.commit();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public static int getItemHeight(Context context) {
		int height = 0;
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			height = settings.getInt(ClientConfig.ITEMVIEW, 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return height;
	}

	/***
	 * @param context
	 * @param r_id
	 * @param itemId
	 * @param itemView
	 * @return
	 */
	public static View getMeasureItem(Context context, int r_id, int itemId, View itemView) {

		LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View conventView = mInflater.inflate(r_id, null);
		itemView = (View) conventView.findViewById(itemId);
		itemView.measure(0, 0);
		return itemView;

	}

	/**
	 * @param context
	 * @param r_id
	 * @param itemId
	 * @return
	 */
	public static View getItem(Context context, int r_id) {
		LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View conventView = mInflater.inflate(r_id, null);
		return conventView;
	}

	/**
	 * @param context
	 */
	public static void capturePicture(Context context) {
		if (context instanceof Activity) {
			if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
				Toast.makeText(context.getApplicationContext(), R.string.sdcard_not_find, Toast.LENGTH_SHORT).show();
				return;
			} else {
				// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				// ((Activity) context).startActivityForResult(intent,
				// Constant.REQUEST_CODE_TAKE_PICTURE);
				File file = new File(ClientConfig.ONEBOX_TAKE_PHOHO_DIC);
				if (!file.exists()) {
					file.mkdirs();
				}
				SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");
				String filename = timeStampFormat.format(new Date()) + ".JPEG";
				Intent imageCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				File out = new File(file.getPath(), filename);
				Uri uri = Uri.fromFile(out);
				imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
				imageCaptureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
				imageCaptureIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
				((Activity) context).startActivityForResult(imageCaptureIntent, Constant.REQUEST_CODE_TAKE_PICTURE);
				ClientConfig.PICTURE_NAME = filename;
			}
		}

	}

	/**
	 * @param uri
	 */
	public static void photoZoom(Context context, Uri uri) {
		if (context instanceof Activity) {
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(uri, ClientConfig.IMAGE_UNSPECIFIED);
			intent.putExtra("crop", "true");
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("outputX", 250);
			intent.putExtra("outputY", 250);
			intent.putExtra("return-data", true);
			((Activity) context).startActivityForResult(intent, Constant.REQUEST_PHOTO_RESULT);
		}
	}

	public static CharSequence formatFileLength(Long length) {
		long size = length;
		if (size < Constant.ONE_KB) {
			return size + "b";
		} else if (size < Constant.ONE_MB) {
			return getRoundFloat(((float) size) / (float) Constant.ONE_KB, 1) + "K";
		} else if (size < Constant.ONE_GB) {
			return getRoundFloat(((float) size) / (float) Constant.ONE_MB, 1) + "M";
		} else {
			return getRoundFloat(((float) size) / (float) Constant.ONE_GB, 1) + "G";
		}
	}

	/**
	 * 
	 * @param flt
	 * @param i
	 * @return
	 */
	public static float getRoundFloat(float flt, int i) {
		if (i > 0) {
			float f = (float) Math.pow(10, i);
			return Math.round(flt * f) / f;
		} else {
			return flt;
		}
	}

	/**
	 * @param context
	 * @return
	 */
	public static int getWindowWidth(Context context) {
		int window_width = 0;
		try {
			Activity activity = (Activity) context;
			WindowManager manager = activity.getWindowManager();
			window_width = manager.getDefaultDisplay().getWidth();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return window_width;
	}

	/**
	 * @param context
	 * @return
	 */
	public static int getWindowHeight(Context context) {
		int window_height = 0;
		try {
			Activity activity = (Activity) context;
			WindowManager manager = activity.getWindowManager();
			window_height = manager.getDefaultDisplay().getHeight();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return window_height;
	}

	/***
	 * @param context
	 */
	public static void restartApp(Context context) {
		// System.exit(0);
		Intent intent = new Intent();
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setClass(context, LoginActivity.class);
		ActivityTaskManager.getInstance().closeAllActivityExceptOne("LoginActivity");
		context.startActivity(intent);
		return;
	}

	/***
	 * @param context
	 */
	public static void setFilePermission(String path, String permission) {
		try {
			String cmd = "chmod -R " + permission + " " + path;
			// Log.d("~", "[VideoDao]cmd:" + cmd);
			Runtime.getRuntime().exec(cmd);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	/**
	 * @param context
	 * @return DisplayMetrics
	 */
	public static DisplayMetrics getScreenWidthAndHeight(Context context) {
		DisplayMetrics dm = context.getResources().getDisplayMetrics();
		return dm;
	}

	/***
	 * @param context
	 * @param pxValue
	 * @return
	 */
	public static int pxTodip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		int dpValue = (int) (pxValue / scale + 0.5f);
		System.out.println("dpValue:" + dpValue);
		return dpValue;
	}

	/**
	 * 
	 * @param context
	 * @param dipValue
	 * @return
	 */
	public static int dipTopx(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	public static void FlowAPICount(Context context, String pkg) {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(context.getString(R.string.flow_count_introduce));

		PackageManager packageManager = context.getPackageManager();
		int PackageUid = 0;
		long totalRx = 0;// b
		long totalTx = 0;// b
		long totalFlow = 0;// b

		for (ApplicationInfo info : packageManager.getInstalledApplications(0)) {
			int uid = info.uid;
			String packageName = info.packageName;
			if (packageName.equals(pkg)) {
				PackageUid = uid;
				break;
			}
		}
		long recv = TrafficStats.getUidRxBytes(PackageUid) * 1024;
		long sent = TrafficStats.getUidTxBytes(PackageUid) * 1024;

		if (sent > 0) {
			totalTx += sent / 1024;
			if (totalTx >= 1024)
				totalTx = totalTx / 1024;
		}

		if (recv > 0) {
			totalRx += recv / 1024;
			if (totalRx >= 1024)
				totalRx = totalRx / 1024;
		}
		totalFlow = totalRx + totalTx;
		String flowShow = context.getString(R.string.flow_count_total) + PublicTools.changeBKM(String.valueOf(totalFlow)) + "\n"
				+ context.getString(R.string.flow_count_recv) + PublicTools.changeBKM(String.valueOf(totalRx)) + "\n"
				+ context.getString(R.string.flow_count_sent) + PublicTools.changeBKM(String.valueOf(totalTx));
		builder.setMessage(flowShow);
		builder.create();
		builder.show();
	}

	public static synchronized String run(String[] cmd, String workdirectory) {
		String result = "";
		try {
			ProcessBuilder builder = new ProcessBuilder(cmd);
			InputStream in = null;
			if (workdirectory != null) {
				builder.directory(new File(workdirectory));
				builder.redirectErrorStream(true);
				Process process = builder.start();
				in = process.getInputStream();
				byte[] re = new byte[1024];
				while (in.read(re) != -1)
					result = result + new String(re);
			}
			if (in != null) {
				in.close();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	private static AlertDialog.Builder builder;

	@SuppressLint("NewApi")
	public static void FlowFileCount(Context context, String pkg) {
		// TODO Auto-generated method stub
		String CATTOOL = "/system/bin/cat";
		String DIRECTORY = "/system/bin/";
		String RECV_NAME = "tcp_rcv";
		String SND_NAME = "tcp_snd";
		String RECV_PATH = "/proc/uid_stat/";
		String SND_PATH = "/proc/uid_stat/";
		//
		if (builder == null) {
			builder = new AlertDialog.Builder(context);
		} else {
			return;
		}

		if (VERSION.SDK_INT > 17) {
			builder.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss(DialogInterface dialog) {
					// TODO Auto-generated method stub
					builder = null;
				}
			});
		} else {
			builder.setOnCancelListener(new OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					// TODO Auto-generated method stub
					builder = null;
				}
			});
		}

		builder.setTitle(context.getString(R.string.flow_count_introduce));

		PackageManager packageManager = context.getPackageManager();
		int packageUid = 0;
		long totalRx = 0;// b
		long totalTx = 0;// b
		long totalFlow = 0;// b

		for (ApplicationInfo info : packageManager.getInstalledApplications(0)) {
			int uid = info.uid;
			String packageName = info.packageName;
			if (packageName.equals(pkg)) {
				packageUid = uid;
				RECV_PATH += (packageUid + "/" + RECV_NAME);
				SND_PATH += (packageUid + "/" + SND_NAME);
				LogUtil.i("SettingActivity", "Package:" + packageName + " | uid:" + uid + "  | RECV_PATH:" + RECV_PATH + " | SND_PATH:" + SND_PATH);
				break;
			}
		}
		try {
			//
			String recv_args[] = { CATTOOL, RECV_PATH };
			String result = PublicTools.run(recv_args, DIRECTORY);
			result = result.split("\n")[0].trim();
			LogUtil.i("SettingActivity", "recv_result:" + result);
			totalRx = Long.parseLong(result);
			//
			String snd_args[] = { CATTOOL, SND_PATH };
			result = PublicTools.run(snd_args, DIRECTORY);
			result = result.split("\n")[0].trim();
			LogUtil.i("SettingActivity", "recv_result:" + result);
			totalTx = Long.parseLong(result);
		} catch (Exception e) {
			// TODO: handle exception
			LogUtil.e("SettingActivity", "e:" + e.toString());
			e.printStackTrace();
		}
		totalFlow = totalRx + totalTx;
		String flowShow = context.getString(R.string.flow_count_total) + PublicTools.changeBKM(String.valueOf(totalFlow)) + "\n"
				+ context.getString(R.string.flow_count_recv) + PublicTools.changeBKM(String.valueOf(totalRx)) + "\n"
				+ context.getString(R.string.flow_count_sent) + PublicTools.changeBKM(String.valueOf(totalTx));
		builder.setMessage(flowShow);
		builder.create();
		builder.show();
	}

	/***
	 * @param inputManager
	 * @param context
	 */
	public static void hideSoftInput(InputMethodManager inputManager, EditText et) {
		if (null != inputManager && null != et) {
			if (null != et.getWindowToken()) {

				inputManager.hideSoftInputFromWindow(et.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			} else {
				// LogUtil.e(, "et.getWindowToken() is null .");
			}
		}
	}

	/***
	 * @param inputManager
	 * @param et
	 */
	public static void showSoftInput(InputMethodManager inputManager, EditText et) {
		if (null != et) {

			if (null != inputManager) {
				et.setFocusableInTouchMode(true);
				et.requestFocus();
				inputManager.showSoftInput(et, 0);
			}
		}
	}

	public static void showKey(final EditText edittext, final Context context) {
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
				// TODO Auto-generated method stub
				// ((InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(0,
				// InputMethodManager.HIDE_NOT_ALWAYS);
				edittext.setFocusableInTouchMode(true);
				// edittext.requestFocus();
				inputManager.showSoftInput(edittext, 0);
			}
		}, 150);
	}

	/**
	 * @param context
	 * @param string
	 */
	public static void openTheBrowser(Context context, String string) {
		try {
			Intent intent = new Intent();
			intent.setAction(Intent.ACTION_VIEW);
			Uri content_url = Uri.parse(string);
			intent.setData(content_url);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent);
		} catch (Exception e) {
			Toast.makeText(context, R.string.browser_open_fail, Toast.LENGTH_SHORT).show();
		}

	}

	/**
	 * @param context
	 * @param packageName
	 * @return
	 */
	public static boolean checkIsFixed(Context context, String packageName) {
		// PackageInfo packageInfo;
		//
		// try {
		// packageInfo = context.getPackageManager().getPackageInfo(
		// packageName, 0);
		// } catch (NameNotFoundException e) {
		// packageInfo = null;
		// e.printStackTrace();
		// }
		// if (packageInfo == null) {
		// return false;
		// } else {
		// return true;
		// }
		return true;
	}

	public static void setUAMADDRESS(Context context, String url) {
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			Editor editor = settings.edit();
			editor.putString(ClientConfig.UAM_ADDRESS, url);
			editor.commit();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public static String getUAMAddress(Context context) {
		String uamAddress = "";
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			uamAddress = settings.getString(ClientConfig.UAM_ADDRESS, "");
			uamAddress = getCorrectUrl(uamAddress);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return uamAddress;
	}

	public static void setUFMADDRESS(Context context, String url) {
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			Editor editor = settings.edit();
			editor.putString(ClientConfig.UFM_ADDRESS, url);
			editor.commit();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public static String getUFMAddress(Context context) {
		String ufmAddress = "";
		try {
			SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			ufmAddress = settings.getString(ClientConfig.UFM_ADDRESS, "");
			ufmAddress = getCorrectUrl(ufmAddress);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ufmAddress;
	}

	@Deprecated
	public static String generatePickCode() {
		String sourse = String.valueOf(System.currentTimeMillis());
		char[] codes = base64Encode(sourse.getBytes());
		int length = codes.length;
		String result = String.valueOf(String.valueOf(codes).substring(length - 9, length - 1));

		return result.toLowerCase();
	}

	public static boolean isAuthiorzationGotoTimeout(Context context) {
		long currentMills = System.currentTimeMillis();
		long time = PublicTools.getExpiredAt(context);
		LogUtil.i("PublicTools", "Expired At: " + longToString(time) + ", CurrentTime: " + longToString(currentMills));
		if (time - currentMills <= Constant.MILLIS_OF_MINIUTE) {
			return true;
		}
		return false;
	}

	public static long getAvaliedTimeMillis(Context context) {
		return PublicTools.getExpiredAt(context) - System.currentTimeMillis();
	}

	public static void reGetTokenByLoginInBanck(Context context) throws ClientException {
		String userName = getLoginUserName(context);
		String password = getLoginUserPassFail(context);
		UserControl.Login(context, userName, password);
	}

	/**
	 * Base64 encode mehtod for weibo request.Refer to weibo development
	 * document.
	 * 
	 */
	public static char[] base64Encode(byte[] data) {
		final char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray();
		char[] out = new char[((data.length + 2) / 3) * 4];
		for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
			boolean quad = false;
			boolean trip = false;
			int val = (0xFF & (int) data[i]);
			val <<= 8;
			if ((i + 1) < data.length) {
				val |= (0xFF & (int) data[i + 1]);
				trip = true;
			}
			val <<= 8;
			if ((i + 2) < data.length) {
				val |= (0xFF & (int) data[i + 2]);
				quad = true;
			}
			out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];
			val >>= 6;
			out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];
			val >>= 6;
			out[index + 1] = alphabet[val & 0x3F];
			val >>= 6;
			out[index + 0] = alphabet[val & 0x3F];
		}
		return out;
	}

	public static String getCorrectUrl(String url) {
		String retUrl = url;
		if (retUrl.endsWith("/")) {
			retUrl = url.substring(0, url.length() - 1);
		}
		return retUrl;
	}
}
